<template>
	<view class="container">
		<navbar></navbar>
		<view class="content-box" :style="'margin-top:' + (statusBarHeight + titleBarHeight) + 'px'">
			<block>
				<textarea
					v-model="ct"
					class="textarea-item"
					show-confirm-bar="false"
					maxlength="4000"
					cursor-spacing="30"
					auto-height
					placeholder="填写笔记内容"
				></textarea>
			</block>
			<scroll-view v-if="0 != type" scroll-x="true" class="scroll-box">
				<view class="scroll-item">
					<block v-if="1 == type">
						<view v-for="(item,i) in pic_arr" :key="i" class="img-box">
							<image :src="item.url" mode="aspectFill" @click="previewClick" :data-i="i"></image>
							<view class="del df" @click.stop="delImg(i)">
								<image src="/static/img/tabbar/33.png"></image>
							</view>
							<view v-if="pic_arr.length > 1" class="sort df">
								<view class="sort-item df" :style="'color:' + (i > 0 ? '#fff' : '#cecece')" @click.stop="onSort(i, 0)">←</view>
								<view class="sort-item df" :style="'color:' + (i < pic_arr.length - 1 ? '#fff' : '#cecece')" @click.stop="onSort(i, 1)">→</view>
							</view>
						</view>
						<view v-if="!video.url" class="img-box file-add df" @click="addImg(1)">
							<image src="/static/img/tabbar/3.png"></image>
							<text>上传图片</text>
						</view>
						<view style="flex-shrink:0;width:20rpx;height:20rpx"></view>
					</block>
					<view v-if="2 == type" class="video-box df">
						<view v-if="!video.url" class="video-item file-add df" @click="addVideo">
							<image src="/static/img/tabbar/3.png"></image>
							<text>上传视频，建议时长</text>
							<text>60秒以内</text>
						</view>
						<block v-else>
							<view class="video-item">
								<video :src="video.url" custom-cache="false"></video>
								<view class="del df" @click="delVideoImg(1)">
									<image src="/static/img/tabbar/33.png"></image>
								</view>
							</view>
							<view v-if="video.img" class="video-item">
								<image :src="video.img" mode="aspectFill"></image>
								<view class="del df" @click="delVideoImg(2)">
									<image src="/static/img/tabbar/33.png"></image>
								</view>
							</view>
							<view v-else class="video-item file-add df" @click="addImg(2)">
								<image src="/static/img/tabbar/3.png"></image>
								<text>视频封面，建议与视频</text>
								<text>尺寸保持一致</text>
							</view>
						</block>
					</view>
					<!-- <block v-if="3 == type">
						<view v-if="!audio.url" class="audio-box file-add df" @click="addFileClick">
							<image src="/static/img/tabbar/3.png"></image>
							<text>上传音频，支持格式mp3和m4a</text>
						</view>
						<view v-else class="file-audio df">
							<image class="audio-bg" :src="audio.cover"></image>
							<view class="audio-mb"></view>
							<view v-if="audio.cover" class="audio-left">
								<image :src="audio.cover"></image>
								<image class="icon xwb" src="/static/img/yw.png"></image>
								<view class="del df" @click="delImg(3)">
									<image src="/static/img/tabbar/33.png"></image>
								</view>
							</view>
							<view v-else class="audio-left file-add df" @click="addImg(3)">
								<image src="/static/img/tabbar/3.png"></image>
								<text>上传封面</text>
							</view>
							<view style="width:calc(100% - 268rpx)">
								<input class="audio-t1" placeholder="点击填写音频名称" placeholder-class="aph" :value="audio.name" @input="audio.name = detail.value" />
								<input class="audio-t2" placeholder="点击填写音频信息" placeholder-class="aph" :value="audio.intro" @input="audio.intro = detail.value" />
							</view>
							<view class="del df" @click="delImg(4)">
								<image src="/static/img/tabbar/33.png"></image>
							</view>
						</view>
					</block> -->
				</view>
			</scroll-view>
			<view class="content-item df">
				<view class="item-adds df" @click="locationClick">
					<image src="/static/img/wz.png"></image>
					<view class="ohto">{{adds.name ? adds.name : '添加位置'}}</view>
				</view>
				<view class="item-count">{{ct.length}}/2000</view>
			</view>
		</view>
		<view class="tags-box">
			<view class="tag-item df" style="border-radius:64rpx" @click="upPopupClick(!0)">
				<image v-if="circle.name" class="icon" :src="circle.avatar" style="border-radius:50%;background:#f8f8f8"></image>
				<image v-else class="icon" style="margin-left:16rpx" src="/static/img/qz2.png"></image>
				<text :style="'color:' + (circle.name ? '#000' : '#999')">{{circle.name ? circle.name : '选择圈子发布'}}</text>
			</view>
			<view v-if="activity.id" class="tag-item df">
				<image class="icon" style="width:60rpx" :src="activity.img" mode="aspectFill"></image>
				<text>{{activity.name}}</text>
			</view>
			<view v-if="(9 == order_type || !order_id) && isNoteShop" class="tag-item df" @click="shopPopupClick(!0)">
				<image class="icon" style="margin-left:16rpx" src="/static/img/ds.png"></image>
				<text style="color:#999">添加商品</text>
			</view>
			<view v-for="(v,i) in goods" :key="i" class="tag-item df">
				<image class="icon" :src="v.product_img" mode="aspectFill"></image>
				<text>{{v.goods_name}}</text>
			</view>
		</view>
		<view class="footer-box bfw bUp">
			<view class="footer-item df">
				<view class="draft" @click="saveDynamic(0)">
					<view class="draft-icon df">
						<image src="/static/img/cg.png"></image>
					</view>
					<view class="tit">存草稿</view>
				</view>
				<view v-if="isUser" class="btn bg2" @click="saveDynamic(1)">发布</view>
				<view v-else class="btn bg1" data-url="center/means" @click="navigateToFun">
					<text>完善账号资料后即可发布笔记，去完善</text>
				</view>
			</view>
		</view>
		<!-- <uni-popup type="bottom" safe-area="!1" ref="shopPopup">
			<view class="popup-box">
				<view class="popup-top df">
					<view class="popup-title">
						<view class="t1">选择商品</view>
						<view class="t2">轻触下方名称以选择相应商品</view>
					</view>
					<view class="popup-close df" @click="shopPopupClick(!1)">
						<image src="/static/img/tabbar/3.png" style="width:20rpx;height:20rpx"></image>
					</view>
				</view>
				<view class="popup-search df">
					<input
						@confirm="searchClick"
						focus="true"
						confirm-type="search"
						placeholder="输入关键词搜索商品"
						placeholder-class="search-ph"
						v-model="kw"
					/>
					<view class="search-btn" @click="searchClick">搜索</view>
				</view>
				<view class="popup-scroll">
					<view v-if="goodsList.length <= 0" class="empty-box df">
						<image src="/static/img/inset/null.png" />
						<view class="e1">暂无商品</view>
						<view class="e2">正在为您制造更多美好的商品</view>
					</view>
					<view class="circle-box">
						<view
							v-for="(item,i) in goodsList"
							:key="i"
							style="border-radius:16rpx"
							:class="['circle-item', 'df', selected && 'active']"
							:data-idx="i"
							@click="goodsClick"
						>
							<image :src="item.product_img" style="border-radius:8rpx" mode="aspectFill"></image>
							<text>{{item.goods_name}}</text>
						</view>
					</view>
				</view>
				<view class="popup-btn" @click="shopPopupClick(!1)">确认保存</view>
			</view>
		</uni-popup> -->
		<uni-popup ref="upPopup" type="bottom" safe-area="!1">
			<view class="popup-box">
				<view class="popup-top df">
					<view class="popup-title">
						<view class="t1">选择一个圈子</view>
						<view class="t2">轻触下方名称以选择相应圈子</view>
					</view>
					<view class="popup-close df" @click="upPopupClick(!1)">
						<image src="/static/img/tabbar/3.png" style="width:20rpx;height:20rpx"></image>
					</view>
				</view>
				<view class="popup-scroll">
					<view v-if="circlearr.length <= 0" class="empty-box df">
						<image src="/static/img/inset/null.png" />
						<view class="e1">暂无圈子</view>
						<view class="e2">还没有加入任何圈子，加入后即可发布</view>
					</view>
					<view class="circle-box">
						<view
							v-for="(item,i) in circlearr"
							:key="i"
							:class="['circle-item', 'df', circle.id == item.id && 'active']"
							:data-i="i"
							@click="circleClick"
						>
							<image :src="item.avatar" mode="aspectFill"></image>
							<text>{{item.name}}</text>
						</view>
					</view>
				</view>
				<view class="popup-btn" @click="upPopupClick(!1)">确认保存</view>
			</view>
		</uni-popup>
		<uni-popup ref="tipsPopup" type="top" mask-background-color="rgba(0, 0, 0, 0)">
			<view class="tips-box df">
				<view class="tips-item">{{tips_title}}</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	const app = getApp();
	const api = require('@/config/api');
	const util = require('@/utils/util');
	export default {
		components: {},
		data() {
			return {
				cid: 0,
				isUser: !1,
				order_id: "",
				order_type: 0,
				goods: [],
				video: { high: 0, wide: 0, url: "", img: "" },
				//audio: { cover: "", url: "", name: "", intro: "", size: 0 },
				adds: { name: "", address: "", latitude: "", longitude: "" },
				circle: { id: "", name: "", avatar: "" },
				activity: { id: "", name: "", img: "" },
				goodsList: [],
				statusBarHeight: app.globalData.statusBarHeight,
				titleBarHeight: app.globalData.titleBarHeight,
				isNoteShop: app.globalData.isNoteShop,
				insetUrl: api.insetUrl,
				id: 0,
				integral: 0,
				ct: '',
				type: 0,
				pic_arr: [],
				topic_ids: [],
				circlearr: [],
				topicarr:  [],
				topic_search: '',
				tips_title: '',
				isaddVideo: false,
				ct_evnt: 0,
				is_fun: true,
			}
		},
		onLoad(options) {
			let that = this;
			if(options.type) this.type = options.type;
			if(options.cid) this.cid = options.cid;
			if (options.id && options.id > 0) {
				that.id = options.id;
				that.getDynamicInfo();
			}
			that.dynamicCircle();
			//that.dynamicTopic();
			util.request(api.configUrl).then(function(res) {
				uni.setStorageSync('config', res.data);
				that.integral = res.data.lnk_jf_ft;
			})
		},
		onShow() {
		  this.isUser = !1;
		  if(uni.getStorageSync("user_info").mobile) this.isUser = !0;
		},
		methods: {
			getDynamicInfo() {
				let that = this;
				util.request(api.getDynamicInfoUrl, {
					id: that.id
				}).then(function(res) {
					that.id = res.data.id;
					that.type = res.data.type;
					that.ct = res.data.content;
					//that.topic_ids = res.data.topic;
					if (that.type == 1) {
						that.pic_arr = res.data.imgs;
					} else if (that.type == 2) {
						that.video.high = res.data.video.high
						that.video.wide = res.data.video.wide
						that.video.url = res.data.video.url
						that.video.img = res.data.video.img
					}
					that.circle = { id: res.data.circle_id, name: res.data.circle_name, avatar: res.data.circle_avatar };
					that.adds.name = res.data.adds;
					that.adds.latitude = res.data.lat;
					that.adds.longitude = res.data.lng;
				});
			},
			dynamicCircle() {
				let that = this;
				util.request(api.dynamicCircleUrl, {
					cid: that.cid
				}).then(function(res) {
					that.circlearr = res.data;
					if(that.cid>0){
						for (let i = 0; i < res.data.length; i++) {
						    if(res.data[i].id==that.cid){
						    	that.circle = {
						    		id: res.data[i].id,
						    		name: res.data[i].name,
						    		avatar: res.data[i].avatar,
						    	}
								break;
						    }
						}
						// res.data.forEach((item, index) => {
						// 	if(item.id==that.cid){
						// 		that.circle = {
						// 			id: item.id,
						// 			name: item.name,
						// 			avatar: item.avatar,
						// 		}
						// 	}
						// });
					}
				});
			},
			dynamicTopic() {
				let that = this;
				util.request(api.dynamicTopicUrl, {
					k: that.topic_search,
				}, 'POST').then(function(res) {
					that.topicarr = res.data;
				});
			},
			saveDynamic() {
				let that = this;
				if(!that.is_fun) return;
				if(that.isaddVideo) return that.opTipsPopup('视频上传中');
				if (2 == that.type) {
					if (!that.video.url) return that.opTipsPopup("视频笔记需添加一个视频哦！");
					if (!that.video.img) return that.opTipsPopup("视频封面不能为空哦！");
				}				
				if (!that.ct) return that.opTipsPopup('笔记内容不能为空哦');
				that.is_fun = false;
				util.request(api.saveDynamicUrl, {
					id: that.id,
					type: that.type,
					content: that.ct,
					circle_avatar: that.circle.avatar,
					circle_id: that.circle.id,
					circle: that.circle.name,
					adds: that.adds,
					imgs: that.pic_arr,
					video: that.video,
					//topic: that.topic_ids,
				}, 'POST').then(function(res) {
					//that.tips_title = res.msg;
					if (res.code == 200) {
						setTimeout(function() {
							app.globalData.dw = 1;
							uni.switchTab({
								url: '/pages/tabbar/center'
							});
						}, 1000);
					}
					that.is_fun = true;
					that.opTipsPopup(res.msg);

				});
			},
			addImg(type) {
				//this.$refs.filePopup.close();
				let that = this;
				let count = 20 - that.pic_arr.length;
				if (type == 2) {
					count = 1;
				}
				uni.chooseImage({
					count: count,
					success: (res) => {
						uni.showLoading({
							title: '上传中...',
							mask: true
						});
						var filePath = res.tempFilePaths;
						if (type == 1) {
							that.type = 1;
							that.getImageInfo(filePath).then(function(imgArr) {
								for (let i in imgArr) {
									util.lnkUploadFile(imgArr[i].url).then(function(fileImg) {
										console.log(fileImg);
										if(fileImg.error == 87014){
											uni.hideLoading();
											uni.showToast({
												title: '图片不合规',
												duration: 2000,
												icon: 'error'
											});
										}else{
											imgArr[i].url = fileImg.data.url;
											if (imgArr.length == parseInt(i) + 1) {
												that.pic_arr = that.pic_arr.concat(imgArr);
												uni.hideLoading();
											}
										}
									});
								}
							});
						} else if (type == 2) {
							util.lnkUploadFile(filePath[0]).then(function(fileImg) {
								console.log(fileImg)
								if(fileImg.error == 87014){
									uni.hideLoading();
									uni.showToast({
										title: '图片不合规',
										duration: 2000,
										icon: 'error'
									});
								}else{
									that.video.img = fileImg.data.url;
									uni.hideLoading();
								}
								
							});
						}
					},
					fail: (err) => {
						console.log('chooseImage fail', err)
					}
				})
			},
			delImg(idx) {
				this.pic_arr.splice(idx, 1);
				//if (this.pic_arr.length <= 0) this.type = 0;
			},
			onSort(idx, type) {
				if (type == 0) {
					this.pic_arr.splice(idx - 1, 0, this.pic_arr[idx]);
					this.pic_arr.splice(idx + 1, 1);
				} else if (type == 1) {
					this.pic_arr.splice(idx + 2, 0, this.pic_arr[idx]);
					this.pic_arr.splice(idx, 1);
				}
			},
			addVideo() {
				//this.$refs.filePopup.close();
				let that = this;
				uni.chooseMedia({
					count: 1,
					mediaType: ['video'],
					success: (res) => {
						that.isaddVideo = true;
						uni.showLoading({
							title: '上传中...',
							mask: true
						});
						that.type = 2;
						var tempFiles = res.tempFiles[0];
						if (tempFiles.tempFilePath) {
							util.lnkUploadFile(tempFiles.tempFilePath, 0).then(function(fileVideo) {
								that.video.high = tempFiles.height;
								that.video.wide = tempFiles.width;
								that.video.url = fileVideo.data.url;
								if (tempFiles.thumbTempFilePath) {
									util.lnkUploadFile(tempFiles.thumbTempFilePath).then(function(
										fileImg) {
										if(fileImg.error == 87014){
											uni.hideLoading();
											that.video.high = 0;
											that.video.wide = 0;
											that.video.url = '';		
											uni.showToast({
												title: '视频不合规',
												duration: 2000,
												icon: 'error'
											});
											
											return ;
										}else{
											that.video.img = fileImg.data.url;
										}
										
									});
								}
								that.isaddVideo = false;
							});
						}
						uni.hideLoading();
					},
					fail: (err) => {
						console.log('chooseMedia fail', err)
					}
				})
			},
			delVideoImg(type) {
				if (type == 1) {
					//this.type = 0;
					this.video = {
						img: ''
					};
				} else if (type == 2) {
					this.$nextTick(() => {
						this.video.img = '';
					})
				}
			},
			getImageInfo(imgs) {
				return new Promise(function(resolve, reject) {
					let imgArr = [];
					for (let v of imgs) {
						uni.getImageInfo({
							src: v,
							success: function(res) {
								let item = {};
								item.url = res.path;
								item.wide = res.width;
								item.high = res.height;
								imgArr.push(item);
								if (imgs.length == imgArr.length) {
									resolve(imgArr);
								}
							}
						});
					}
				});
			},
			locationClick() {
				let that = this;
				uni.chooseLocation({
					success: function(res) {
						that.adds = res;
					}
				});
			},
			circleClick(e) {
				let i = e.currentTarget.dataset.i;
				if(this.circlearr[i].id == this.circle.id){
					this.circle.id = "";
					this.circle.name = "";
					this.circle.avatar = "";
				}else{
					this.circle = {
						id: this.circlearr[i].id,
						name: this.circlearr[i].name,
						avatar: this.circlearr[i].avatar,
					}
				}
			},
			onKeyInput(e) {
				//this.topic_search = e.detail.value
				this.dynamicTopic();
			},
			handleInputBlur(event) {
				// 获取输入框当前的光标位置
				let cursor = event.detail.cursor;
				this.ct_evnt = cursor;
				// 获取输入框的值
				// let value = this.inputValue;
				// // 在光标位置后追加字符串
				// this.inputValue = value.substring(0, cursor) + '追加的字符串' + value.substring(cursor);
				// // 重设光标位置
				// event.target.selectionStart = cursor + '追加的字符串'.length;
				// event.target.selectionEnd = cursor + '追加的字符串'.length;
			},
			// topicaddClick() {
			// 	if(this.topic_ids.includes(this.topic_search))
			// 	{
			// 		//this.topic_ids = this.topic_ids.filter(item => item !== n);
			// 	}else{
			// 		this.topic_ids.push(this.topic_search);
			// 	}
				
			// },
			topicClick(n) {
				// let i = e.currentTarget.dataset.i;
				// let n =  this.topicarr.data[i].name;
				if(this.topic_ids.includes(n))
				{
					this.topic_ids = this.topic_ids.filter(item => item !== n);
				}else{
					this.topic_ids.push(n);
				}
				
				
				// // 获取输入框当前的光标位置
				// let cursor = this.ct_evnt;
				// console.log(cursor);
				// // 获取输入框的值
				// let value = this.ct;
				// // 在光标位置后追加字符串
				// let n_n = "#" + n;
				// this.ct = value.substring(0, cursor) + n_n + value.substring(cursor);
				// // 重设光标位置
				// this.ct_evnt = cursor + n_n.length;

			},
			toCircle() {
				uni.switchTab({
					url: '/pages/tabbar/circle'
				})
			},
			// openFile() {
			// 	this.$refs.filePopup.open();
			// },
			openTopic() {
				this.topic_search = '';
				this.$refs.topicPopup.open();
				this.dynamicTopic();
			},
			upPopupClick(i) {
			  if(i) this.$refs.upPopup.open();
			  if(!i) this.$refs.upPopup.close();
			},

			openTipsPopup() {
				this.$refs.addPopup.open();
			},
			closeTipsPopup() {
				this.$refs.addPopup.close();
			},
			previewClick(e) {
				let t = e.currentTarget.dataset.i;
				o = [];
				for (let i of this.imgs) o.push(i.url);
				i.index.previewImage({ current: t, urls: o });
			},
			navigateToFun(e) {
				
				let url = e.currentTarget.dataset.url;
				util.navigateTo({
					url: '/pages/' + url
				})
			},
			ctInput(e){
				this.ct = e.detail.value;
			},
			opTipsPopup(title,time = 1500) {
				let that = this;
				that.tips_title = title;
				that.$refs.tipsPopup.open();
				setTimeout(function () {
					that.$refs.tipsPopup.close();
				}, time);
			},
		},
	}
</script>

<style lang="scss">
	@import url("/static/css/note/add.css");
	
</style>